/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.cmd;

import org.jivesoftware.smack.XMPPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.Command;
import com.foreveross.bsl.Config;
import com.foreveross.bsl.openfire.OpenfireClient;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-12-6
 *
 */
public class OpenfireMsgSendCmd implements Command {
	
	private static final Logger log = LoggerFactory.getLogger(OpenfireMsgSendCmd.class);

	private final Config config;
	private OpenfireClient sender;
	
	public OpenfireMsgSendCmd(Config config) {
		this.config=config;
		this.sender=new OpenfireClient(this.getHost(), this.getPort());
		this.sender.setUsername(this.getSenderUsername());
		this.sender.setPassword(this.getSenderPassword());
		try {
			this.sender.login();
		} catch (XMPPException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void execute() {
		int targetCount=this.getTargetCount();
		int repeat=this.getRepeat();
		String msg=this.getMsg();
		long tick=System.currentTimeMillis();
		log.debug("开始发送消息...");
		for(int j=1; j<=targetCount; j++){
			String jid=this.buildJid(OpenfireClient.PREFIX_USERNAME+j);
			log.debug("发送消息到目标:{}",jid);
			for(int i=1; i<=repeat; i++){
				try {
					sender.sendMessage(jid, msg);
				} catch (Exception e) {
					log.error("发送消息到目标"+jid+"出错", e);
				}
			}
		}
		log.info("发送{}个客户端，{}遍，耗时{}ms", targetCount, repeat, System.currentTimeMillis()-tick);
	}
	
	private String buildJid(String username){
		StringBuilder sb=new StringBuilder(username);
		sb.append("@").append(this.getJidDomain()).append("/Push_Test");
		return sb.toString();
	}

	/**
	 * @return the fromIndex
	 */
	public int getFromIndex() {
		return Integer.parseInt(this.config.getProperty("openfire.sender.fromIndex", "1"));
	}

	/**
	 * @return the repeat
	 */
	public int getRepeat() {
		return Integer.parseInt(this.config.getProperty("openfire.sender.repeat", "1"));
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return this.config.getProperty("openfire.sender.msg", "Are u fucking sure!");
	}
	
	/**
	 * @return the host
	 */
	public String getHost() {
		return this.config.getProperty("openfire.host", true);
	}

	/**
	 * @return the port
	 */
	public int getPort() {
		return Integer.parseInt(this.config.getProperty("openfire.port", "5222"));
	}

	public String getSenderUsername(){
		return this.config.getProperty("openfire.sender.username", true);
	}
	
	public String getSenderPassword(){
		return this.config.getProperty("openfire.sender.password", true);
	}
	
	public String getJidDomain(){
		return this.config.getProperty("openfire.jid.domain", true);
	}
	
	public int getTargetCount() {
		return Integer.parseInt(this.config.getProperty("openfire.sender.targetCount", "1"));
	}

}
